package com.zilue.payment.gateway.paramter;

import com.zilue.payment.gateway.annotation.ParameterFiledCheck;
import org.apache.commons.lang3.StringUtils;

import java.lang.reflect.Field;
import java.util.regex.Pattern;

/**
 * Created by zilue on 2017/4/5.
 */

public class BaseParameter {

    public ParameterCheckResult ParameterCheck() {
        Class<? extends BaseParameter> clazz = this.getClass();
        Field[] declaredFields = clazz.getDeclaredFields();

        for (Field field : declaredFields) {
            field.setAccessible(true);
            String name = field.getName();
            try {
                Object value = field.get(this);

                ParameterFiledCheck annotation = field.getAnnotation(ParameterFiledCheck.class);
                if (annotation == null) {
                    continue;
                }
                String regex = annotation.regex();
                if (StringUtils.isEmpty(regex)) {
                    continue;
                }
                String description = annotation.description();
                description = StringUtils.isEmpty(description) ? "不合法" : description;
                Pattern pattern = Pattern.compile(regex);
                boolean matches = pattern.matcher(String.valueOf(value == null ? "" : value)).matches();
                if (!matches)
                    return ParameterCheckResult.createErrorResult(name, description);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
                System.err.println("参数校验异常");
                return ParameterCheckResult.createErrorResult(name, "校验异常");
            }
        }
        ParameterCheckResult complicated = this.complicated();
        if (!complicated.isStatus())
            return complicated;

        return ParameterCheckResult.createSuccess();
    }

    /**
     * 复杂检查
     *
     * @return
     */
    public ParameterCheckResult complicated() {
        return ParameterCheckResult.createSuccess();
    }
}
